<?


class CTRLmedia extends CONTROL {

	function __construct( $vars ) {
		
		$this->_addvars( $vars );

		if( $this->action != "list" )
			$this->create_object();
	}


	var $stream_sources = array( "youtube"=>"youtube", "vimeo"=>"vimeo" );


#	Object list.
	function filter_list() {
		global $Request;
		
		return $this->{ "filter_list_" . array_pop( explode( ".", $this->vars->type ))}();

	}


	function filter_list_img() {
		global $Request;
					
		return "
		ref.seed([
			new Element( 'h1' ).update( '" . ucfirst( $this->vars->descr ) . "' ),
			new Dropbox({ descr:'{$this->vars->descr}', type:'{$this->vars->type}', action:'win', blank:'add image', uptype:'media', floats:" . 
				$Request->parse_list( "ID, ID as key_0, <%lang:nameid%> as key_1, active as key_2", true ) ." })
		]);";
				
	}


	function filter_list_file() {
		global $Request;
					
		return "
		ref.seed([
			new Element( 'h1' ).update( '" . ucfirst( $this->vars->descr ) . "' ),
			new Dropbox({ descr:'{$this->vars->descr}', type:'{$this->vars->type}', action:'win', blank:'add file', uptype:'file', floats:" . 
				$Request->parse_list( "ID, ID as key_0, <%lang:nameid%> as key_1, active as key_2", true ) ." })
		]);";
				
	}


	function filter_list_stream() {
		global $Request;
		
		return "
			ref.seed([
			new Element( 'h1' ).update( '" . ucfirst( $this->vars->descr ) . "' ),
			new Dropbox({ descr:'{$this->vars->descr}', type:'{$this->vars->type}', action:'win', blank:'add stream', uptype:'stream', floats:" . 
				$Request->parse_list( "ID, ID as key_0, <%lang:nameid%> as key_1, active as key_2", true ) ." })
			]);";		
	
	}


#	New Object.
	function filter_new() {
		global $Object;
		
		if( $this->parent ) $new = "$('$this->parent').seed([" . $Object->render_core_json() . "], 0);";
		
		// deprecated!!
		if( $this->vars->uptype == "stream" )
			$Object->set( "meta", array( "source" => "youtube" ), 1 );

		return $new . $this->filter_edit();
	}

	
#	Edit Object.

	// case for different media filters
	function filter_edit() {
	
		return $this->{ "filter_edit_" . array_pop( explode( ".", $this->vars->type ))}();
	
	}
	
	// filter media 
	function filter_edit_img() {
		global $Engine, $Object;
		
		return "
		ref.seed([
			
			new Element( 'h1' ).update( \"Beheer {$this->vars->type} '". (( $Object->get( "nameid" ) )? $Engine->text->get( $Object->get( "nameid" ) ) : $Object->id ) . "'\" ),
			new Textfield({ descr:'name {$this->vars->type}', type:'{$this->vars->type}', parentid:{$Object->id}, textid:". $Object->get( "nameid" ) .", values:" . 
				json_encode( $Engine->text->filter( $Object->get( "nameid" ) )) ." }),
			new Htmlfield({ descr:'text {$this->vars->type}', type:'{$this->vars->type}', parentid:{$Object->id}, textid:". $Object->get( "textid" ) .", values:" . 
				json_encode( $Engine->text->filter($Object->get( "textid" ), 'long' )) ." })
		]);";

	}
	
	// filter files
	function filter_edit_file() {
		global $Engine, $Object;
		
		return "
		ref.seed([
			
			new Element( 'h1' ).update( \"Beheer {$this->vars->type} '". (( $Object->get( "nameid" ) )? $Engine->text->get( $Object->get( "nameid" ) ) : $Object->id ) . "'\" ),
			new Textfield({ descr:'name {$this->vars->type}', type:'{$this->vars->type}', parentid:{$Object->id}, textid:". $Object->get( "nameid" ) .", values:" . 
				json_encode( $Engine->text->filter( $Object->get( "nameid" ) )) ." }),
			new Htmlfield({ descr:'text {$this->vars->type}', type:'{$this->vars->type}', parentid:{$Object->id}, textid:". $Object->get( "textid" ) .", values:" . 
				json_encode( $Engine->text->filter($Object->get( "textid" ), 'long' )) ." }),
			new Options({ descr:'Informatie', active:true, floats: [
				new Shift({ type:'{$this->vars->type}', descr:'active', value:{$Object->get( 'active' )}, field:'active', objid:{$Object->id} })
			]})
		]);";

	}
	
	// filter streams
	function filter_edit_stream()  {
		global $DB, $Engine, $Object;
		
		foreach( $this->stream_sources as $key => $value ) {
			$options[] = array( "key" => $key, "value"=> $key );
		}
				
		return "
		ref.seed([
			
			new Element( 'h1' ).update( \"Beheer {$this->vars->type} '". (( $Object->get( "nameid" ) )? $Engine->text->get( $Object->get( "nameid" ) ) : $Object->id ) . "'\" ),
			new Element( 'span', {id: ref.id + '.name'} ).update( '{$Object->get( 'name' )}'),
			new Options({ descr:'Informatie', active:true, floats: [
				new Select({ type: '{$this->vars->type}', descr:'type mediaprovider', objid: {$Object->id}, field:'meta.source', key: '{$Object->get( 'source' )}', opts: " . json_encode( $options ) . " }),
				new Ajxfield({ type:'{$this->vars->type}', parenttype: '" . $Object->parenttype . "', parentid: '" . $Object->parentid . "', descr:'source id', ref:ref.id, id:{$Object->id}, field:'meta.id', value:'{$Object->get('id')}', requestfunc:'pull' }),
				new Shift({ type:'{$this->vars->type}', descr:'active', value:{$Object->get( 'active' )}, field:'active', objid:{$Object->id} })
			]})
		]);";
	}


#	Shift (alter column value).
	function filter_ajax() {
		global $DB, $Request;
		
		if( $Request->vars->requestfunc )
			$comment = $this->{ $Request->vars->requestfunc }();
		
		else 
			$comment = ( $Request->ajax() )? "option modified":"warning: failed";

		return $this->comment( $comment );
	}
	
#	Social function: pull	
	function pull() {
		global $Request, $Object, $Engine, $DB;
		
		// get variables
		$source 	= $Object->values['meta']->source;
		$objid		= $Request->vars->id;
		
		// add to group (if group is set)
		if ( $Request->vars->parentid && $Request->vars->parenttype )
			
			$DB->set_reference( $Request->vars->parenttype, (int) $Request->vars->parentid, $Request->vars->type, (int) $objid );
			//$DB->query( "INSERT INTO glue_object (parenttype,parentid,objtype,objid,rank ) VALUES ('".(int) $DB->type($Request->vars->parenttype) ."', '".(int) $Request->vars->parentid ."', '". (int) $DB->type($Request->vars->type) . "', $objid, 5 )" );
		

		// check type of source
		if ( $source == 'vimeo' ) {
		
			// check if file exists
			if ( $this->url_exists('http://vimeo.com/api/v2/video/' . $Request->vars->value . '.xml' )) {
				
				// get title & thumbnail
				$vimeo = new Vimeo();
				$info	= (object) $vimeo->video_info( $Request->vars->value, array('id','title','url','thumbnail_large'));
								
				// upload image to server
				$this->copy_thumb( $info->thumbnail_large, ROOT . ACCOUNT . '/www/DB/media/', $objid );
			
				// set or update title						
				$Object->set( 'nameid', ( string ) $Engine->text->set( $info->title, (int) $Object->values['nameid'] ));
				echo "$('" . $Request->vars->ref . ".name').update('" . $info->title . "')";
			
				// update id in meta
				$Object->set('meta', array( 'id'=>$Request->vars->value, 'source'=> $source ), 1);
			
				return 'vimeo found';
			
			} else {
				
				return 'vimeo not found';
			
			}
			
		}
		
		else {
		
			$source = 'youtube';
			
			// check if file exists
			if ( $this->url_exists('http://gdata.youtube.com/feeds/api/videos/' . (string) $Request->vars->value )) {
				
				// get title & thumbnail
				$youtube = new Youtube();
				
				// get title
				$title 	= (object) $youtube->video_info($Request->vars->value, 'title');
				$t 		= '$t'; 
				$title 	= $title->$t;
				
				
				// get thumbnail
				$thumb 	= (object) $youtube->video_info($Request->vars->value, 'media$group');
				$media 	= 'media$thumbnail'; 
				$thumb 	= $thumb->$media;
				$thumb	= $thumb[0]->url;

				// upload image to server
				$this->copy_thumb( $thumb, ROOT . ACCOUNT . '/www/DB/media/', $objid );
			
				// set or update title						
				$Object->set( 'nameid', ( string ) $Engine->text->set( $title, (int) $Object->values['nameid'] ));
				echo "$('" . $Request->vars->ref . ".name').update('" . $title . "');";
			
				// update id in meta
				$Object->set('meta', array( 'id'=>$Request->vars->value, 'source'=> $source), 1);
			
				return 'youtube found';
			
			} else {
				
				return 'youtube not found';
			
			}
			
		}
		
		
	}
	
	
	/**
	 * 	check if url exists
	 *
	 *	@param		string
	 *	@return		int
	 */
	function url_exists($url) {
		@ $headers = get_headers($url);
    	return preg_match('/^HTTP\/\d\.\d\s+(200|301|302)/', $headers[0]);
	}  
	
	
	
	/**
	 *	copy thumbnail to server 
	 *
	 *	@param		string thumbnail
	 *	@param		string destination
	 *	@return		string new image 
	 */
	function copy_thumb( $source, $dest, $name ) {
	
		$image 		= @file_get_contents( $source );
		$new_img 	= fopen ( $dest . $name . '.jpg', 'w');
		fwrite ( $new_img, $image );
		fclose ( $new_img ); 
		
		return $new_img;
	}
}	

/** 
 * YOUTUBE CLASS
 *
 * This can be used to communicate with youtube (http://youtube.com)
 *
 * This is only the beginning of a youtube class that makes it able to easily communicate with youtube.. should be expanded in the future!
 *
 * @copyright 	oneDot only <we@onedotonly.be>
 * @author		Pieter Van Peteghem <pieter@onedotonly.be>
 * @version		version 0.01 beta
 *
 * @copyright	Copyright (c) 2010, oneDot only. All rights reserved.
 * @license		BSD License
 */

class Youtube {


	/**
	 *	variables that are used within the class
	 */
	var $youtube_url = 'http://gdata.youtube.com/feeds/api/';



	/**
	 * 	ask json info about video
	 *
	 *	@param		integer, id of the vimeo video
	 *	@param		string, markup return language (standard json, could be xml)
	 *	@return		array
	 */
	function get_video( $id, $output = 'json' ) {
	
		$video	= json_decode ( file_get_contents( $this->youtube_url . 'videos/' . $id . '?alt=' . $output ));
		return $video->entry;
	
	} 



	/**
	 * 	youtube request for info about movie
	 *
	 * 	@param		integer, id of the video
	 * 	@param		string / array with values you want to get
	 *	@return		string / array (defined by what)
	 */
	function video_info ( $id, $what ) {
	
		// get video information
		$video 	= $this->get_video( $id );
		
		// check for array => multiple values
		if ( is_array ( $what )) {
			foreach ($what as $info) {
				$return[$info] = $video->$info;
			}
			return $return;
			
		// single value 
		} else {
			return $video->$what;
		}
	}


}

/** 
 * VIMEO CLASS
 *
 * This can be used to communicate with vimeo (http://vimeo.com)
 *
 * This is only the beginning of a vimeo class that makes it able to easily communicate with vimeo.. should be expanded in the future!
 *
 * @copyright 	oneDot only <we@onedotonly.be>
 * @author		Pieter Van Peteghem <pieter@onedotonly.be>
 * @version		version 0.01 beta
 *
 * @copyright	Copyright (c) 2010, oneDot only. All rights reserved.
 * @license		BSD License
 */

class Vimeo {

	/**
	 *	variables that are used within the class
	 */
	var $vimeo_url	= 'http://vimeo.com/api/v2/';



	/**
	 * 	ask json info about video
	 *
	 *	@param		integer, id of the vimeo video
	 *	@param		string, markup return language (standard json, could be xml)
	 *	@return		array
	 */
	function get_video( $id, $output = 'json' ) {
	
		$video	= json_decode ( file_get_contents( $this->vimeo_url . 'video/' . $id . '.' . $output ));
		return $video[0];
	
	} 



	/**
	 * 	vimeo request for info about movie
	 *
	 * 	@param		integer, id of the video
	 * 	@param		string / array with values you want to get
	 *	@return		string / array (defined by what)
	 */
	function video_info ( $id, $what ) {
	
		// get video information
		$video 	= $this->get_video( $id );
		
		// check for array => multiple values
		if ( is_array ( $what )) {
			foreach ($what as $info) {
				$return[$info] = $video->$info;
			}
			return $return;
			
		// single value 
		} else {
			return $video->$what;
		}
	}
}
